package gl.android.biyiqing.fragment;

import gl.App;
import gl.android.biyiqing.FragmentContainerActivity;
import gl.android.biyiqing.R;
import gl.android.biyiqing.api.API;
import gl.android.biyiqing.bean.BYQUserInfo;
import gl.android.biyiqing.bean.KV;
import gl.android.biyiqing.competent.OnToFollowUserClickListener;
import gl.android.biyiqing.competent.OnToGreetItemClickListener;
import gl.android.biyiqing.event.EventCalnceFollow;
import gl.android.biyiqing.event.EventOnFollow;
import gl.anima.PotinToCover;
import gl.common.AjaxCallBackProxy;
import gl.common.BaseControl;
import gl.common.UserManger;
import gl.func.updoladPicture.SelectPictureActivity;
import gl.uitls.AndroidSystemUtils;
import gl.uitls.AndroidUtil;
import gl.uitls.Lg;
import gl.uitls.Tip;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import net.tsz.afinal.http.AjaxCallBack;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RadioButton;
import android.widget.ScrollView;
import android.widget.TextView;
import de.greenrobot.event.EventBus;

public class OtherUserFragment extends UserInfoFragment {
	// Content View Elements

	// Content View Elements
	OnClickListener buy = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			goBuyActy(getActivity());
		}
	};
	OnClickListener newMessage = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			geNewMessage(getActivity());
		}
	};

	public void goBuyActy(Context context) {
		Intent intent = new Intent(context, FragmentContainerActivity.class);
		Bundle bundle = new Bundle();
		bundle.putString(FragmentContainerActivity.BaseFragmentClassName,
				GiftFragment.class.getName());

		bundle.putString(BaseFragment.KEY_TO_USER_ID, userID);
		intent.putExtras(bundle);
		context.startActivity(intent);
	}

	public void geNewMessage(Context context) {
		Intent intent = new Intent(context, FragmentContainerActivity.class);
		Bundle bundle = new Bundle();
		bundle.putString(FragmentContainerActivity.BaseFragmentClassName,
				MessageChatFragment.class.getName());
		bundle.putString(BaseFragment.KEY_TO_USER_ID, userID);
		intent.putExtras(bundle);
		context.startActivity(intent);
	}

	private TextView mNick;
	private TextView mLocal;
	private ScrollView mPager;
	private TextView mDubai;
	private LinearLayout mCondubai;
	private TextView mXinxi;
	private LinearLayout mConxinxi;
	private TextView mZeyou;
	private LinearLayout mConzeyou;
	private gl.android.widget.radio.RoundRadioGroup mRoundRadioGroup1;
	private RadioButton mZhuanhao;
	private RadioButton mHongniang;
	private RadioButton mIv_xiexin;
	private RadioButton mIv_buygift;
	private LinearLayout album;
	private ImageView mAtacor;
	private TextView mtv_condubai;
	private View hi;
	private ImageView follow;
	private View ic_flag_nearby;

	// End Of Content View Elements

	private void bindViews() {

		mAtacor = (ImageView) findViewById(R.id.imageView1);
		mNick = (TextView) findViewById(R.id.nick);
		mLocal = (TextView) findViewById(R.id.local);
		ic_flag_nearby = findViewById(R.id.imageView10);
		mPager = (ScrollView) findViewById(R.id.pager);
		mDubai = (TextView) findViewById(R.id.dubai);
		mCondubai = (LinearLayout) findViewById(R.id.condubai);
		mXinxi = (TextView) findViewById(R.id.xinxi);
		mConxinxi = (LinearLayout) findViewById(R.id.conxinxi);
		mZeyou = (TextView) findViewById(R.id.zeyou);
		mtv_condubai = (TextView) findViewById(R.id.tv_condubai);
		mConzeyou = (LinearLayout) findViewById(R.id.conzeyou);
		album = (LinearLayout) findViewById(R.id.album);
		mRoundRadioGroup1 = (gl.android.widget.radio.RoundRadioGroup) findViewById(R.id.roundRadioGroup1);
		mZhuanhao = (RadioButton) findViewById(R.id.zhuanhao);
		mHongniang = (RadioButton) findViewById(R.id.hongniang);
		mIv_xiexin = (RadioButton) findViewById(R.id.iv_xiexin);
		mIv_xiexin.setOnClickListener(newMessage);

		mIv_buygift = (RadioButton) findViewById(R.id.iv_buygift);
		mIv_buygift.setOnClickListener(buy);
		follow = (ImageView) findViewById(R.id.follow);
		hi = findViewById(R.id.hi);
		
	}

	public OtherUserFragment() {
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
	}

	final String type_avator = "1-";
	final String type_album = "2-";
	private boolean isfriend;

	class AjaxCallBackForUpload extends AjaxCallBack<String> {
		String temp_type;

		AjaxCallBackForUpload(String type) {
			temp_type = type;
		}

		final String UPLOADFAIL = "上传失败";

		@Override
		public void onSuccess(String t) {
			super.onSuccess(t);
			Lg.i(t);
			try {
				if (!new JSONObject(t).getBoolean("ret")) {
					Tip.show(UPLOADFAIL);
				}
				else {
					if (temp_type == type_album) {
						// EventBus.getDefault().post(
						// new RefreshAlbum(
						// UserManger.getInstance().userid));
						initData();
					}
				}

			} catch (Exception e) {
				e.printStackTrace();
				onFailure(e, 0, "");
			}
		}

		@Override
		public void onFailure(Throwable t, int errorNo, String strMsg) {
			super.onFailure(t, errorNo, strMsg);
			Tip.show(UPLOADFAIL);
		}
	};
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		EventBus.getDefault().register(this);
	}
	@Override
	public void onDetach() {
		super.onDetach();
		EventBus.getDefault().unregister(this);
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.fragment_otheruser_info,
				container, false);
		bindViews();
		
		initData();
		return rootView;
	}

	private void initUserState(JSONObject jo) throws JSONException {
		
		int iconId = R.drawable.ic_vip;
//		用户组ID：1普通会员 2高级会员 3.皇冠会员 3钻石会员、用户形象照
		
		switch (jo.optInt(BYQUserInfo.KEY_GROUPID, 0)) {
		case 1:
			iconId = R.drawable.ic_member_general;
			break;
		case 2:
			iconId = R.drawable.ic_member_crystal;
			break;
		case 3:
			iconId = R.drawable.ic_member_crown;
			break;
		case 4:
			iconId = R.drawable.ic_member_diamond;
			break;
		}
		jo.put(BYQUserInfo.KEY_GROUP, iconId);
//		jo.put(BYQUserInfo.KEY_ONLINE, status);
		
		if (jo.optInt("online", 0)==1) {
			jo.put(BYQUserInfo.KEY_VIP_UNIT, R.drawable.ic_vip);
		}else{
			jo.put(BYQUserInfo.KEY_VIP_UNIT,R.drawable.tran_shap12dp );
		}
		;
		
		final String URI = "android.resource://"+getActivity().getPackageName()+"/";
		display(rootView.findViewById(R.id.imageView7), URI + jo.optInt(BYQUserInfo.KEY_ONLINE));//ic_online_phone
		display(rootView.findViewById(R.id.imageView8),URI + jo.optInt(BYQUserInfo.KEY_VIP_UNIT));//ic_vip
		display(rootView.findViewById(R.id.imageView9), URI + jo.optInt(BYQUserInfo.KEY_GROUP));//ic_member_diamond
		display(rootView.findViewById(R.id.imageView10), URI + jo.optInt(BYQUserInfo.KEY_NEARBY));//ic_place
		
		
	}

	private void display(View findViewById, String string) {
		try {
			
			((ImageView)findViewById).setImageURI(Uri.parse(string));
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	private void initData() {

		BaseControl.get(API.URL + "GetUserInfo?userid=%s&localuserid=%s",
				new AjaxCallBackProxy() {
					@Override
					public void onSuccess(String t) {
						if (!isValueFragment()) {
							return;
						}
						super.onSuccess(t);
						try {
							OtherUserFragment.this.data = t;
							final JSONObject jsonObject = new JSONObject(t);
							final JSONArray jsonArray = jsonObject
									.getJSONArray("data");
							if (jsonArray == null) {
								return;
							}


							hi = findViewById(R.id.hi);
							hi.setOnClickListener(new OnToGreetItemClickListener(
									getActivity(), userID));

							final Object userphoto = jsonObject
									.get("userphoto");
							initUserinfo(jsonArray.getJSONObject(0).toString());
							
							follow.setOnClickListener(new OnToFollowUserClickListener(
									getActivity(), userID, isfriend));
							new Handler().postDelayed(new Runnable() {

								@Override
								public void run() {
									initAlbumData(userphoto.toString());

								}
							}, 333);

						} catch (Exception e) {
							e.printStackTrace();
							onFailure(e, 0, e.getMessage());
						}finally{
							findViewById(R.id.login_status).setVisibility(View.GONE);
						}
					}
					@Override
					public void onFailure(Throwable t, int errorNo,
							String strMsg) {
						super.onFailure(t, errorNo, strMsg);
						findViewById(R.id.login_status).setVisibility(View.GONE);
					}
				}, userID, UserManger.getInstance().userid);

	}

	public void onEvent(EventCalnceFollow isfriend) {
		this.isfriend = false;
		follow.setImageResource(R.drawable.ic_btn_hello_n);
		follow.setOnClickListener(new OnToFollowUserClickListener(
				getActivity(), userID, this.isfriend ));
	}
	public void onEvent(EventOnFollow isfriend) {
		this.isfriend = true;
		follow.setImageResource(R.drawable.ic_btn_hello_p);
		follow.setOnClickListener(new OnToFollowUserClickListener(
				getActivity(), userID, this.isfriend ));
	}

	public void initUserinfo(String data) {
		if (data == null) {
			return;
		}
		final JSONObject jo;
		try {
			jo = new JSONObject(data);
			App.mFBitmap
					.display(mAtacor, API.IMAGEURL + jo.optString("avatar"));
			mNick.setText(jo.optString("username")+"(ID:"+userID+")");
			initUserState(jo);
			float nearby = 0;
			try {
				nearby = Float.parseFloat(jo.opt("nearby").toString());
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (nearby <= 0) {
				mLocal.setText("");
				ic_flag_nearby.setVisibility(View.GONE);
			}
			else {
				mLocal.setText("" + nearby);
				ic_flag_nearby.setVisibility(View.VISIBLE);
			}
			isfriend = jo.optInt("isFriend") == 1;
			if (isfriend) {
				// 0 no 1 yes
				follow.setImageResource(R.drawable.ic_btn_hello_p);
			}
			else {
				follow.setImageResource(R.drawable.ic_btn_hello_n);
			}
			mHongniang.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					AndroidUtil.genDialog(getActivity(),
							"红娘为您牵缘,将会拨打一个红娘电话(话费由电话运营商收费)", "拨打红娘电话",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									AndroidSystemUtils.Call(getActivity(),
											jo.optString("redgril"));
								}
							});
				}
			});
			mZhuanhao.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					if (!TextUtils.isEmpty(jo.optString("specialissue"))) {
						AndroidSystemUtils.Call(getActivity(),
								jo.optString("specialissue"));
					}
					else {
						Tip.show("还没有开通超级副号");
					}

				}
			});
			mtv_condubai.setText("\t\t" + jo.optString("monolog"));
			Iterator<String> keys = jo.keys();
			while (keys.hasNext()) {
				String name = keys.next();
				if ("avatar".equals(name) || "monolog".equals(name)) {
					continue;
				}
				// addInfo(mConxinxi, name, jo.opt(name).toString());

			}
			// 个人详细信息
			// HashMap<String, KV> maps = BYQUserInfo
			// .getUserInfo(OtherUserFragment.this.data);
			HashMap<String, KV> maps = BYQUserInfo
					.formatBaseInfo2HashMap(new JSONObject(
							OtherUserFragment.this.data).getJSONArray("data")
							.getJSONObject(0));
			Set<String> set = maps.keySet();
			final Iterator<String> iterator = set.iterator();
			while (iterator.hasNext()) {
				final String next = iterator.next();
				final KV kv = maps.get(next);
				addInfo(mConxinxi, kv.keyChinese, kv.valueChinese);
			}
			// 择友要求
			HashMap<String, KV> mapsgetZEYOUInfo = BYQUserInfo
					.getZEYOUInfo(OtherUserFragment.this.data);
			Set<String> setgetZEYOUInfo = mapsgetZEYOUInfo.keySet();
			final Iterator<String> iteratorgetZEYOUInfo = setgetZEYOUInfo
					.iterator();
			while (iteratorgetZEYOUInfo.hasNext()) {
				final String next = iteratorgetZEYOUInfo.next();
				final KV kv = mapsgetZEYOUInfo.get(next);
				addInfo(mConzeyou, kv.keyChinese, kv.valueChinese);
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	public void initinfo(LinearLayout view, String data) {
		if (data == null) {
			return;
		}
		JSONObject jo;
		try {
			jo = new JSONArray(data).getJSONObject(0);
			Iterator<String> keys = jo.keys();
			while (keys.hasNext()) {
				String name = keys.next();
				addInfo(view, name, jo.opt(name).toString());
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	protected void addInfo(LinearLayout container2, String name, Object opt) {
		View view = getActivity().getLayoutInflater().inflate(
				R.layout.item_edit_userinfo, null);
		TextView tv = (TextView) view.findViewById(R.id.textView1);
		tv.setText(name.concat(":"));
		TextView et = (TextView) view.findViewById(R.id.editText1);
		et.setText(opt == null ? "" : opt.toString());
		et.setEnabled(false);
		et.setTextColor(getResources().getColor(R.color.graydrak));
		LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT);
		container2.addView(view, lp);
	}

	private void initAlbumData(String data) {
		if (data == null) {
			return;
		}
		JSONArray jo;
		try {
			jo = new JSONArray(data);
			album.removeAllViews();
			if (jo.length() == 0) {
				addViewToGrid(album, "", "", null);
			}
			for (int i = 0; i < jo.length(); i++) {
				addViewToGrid(
						album,
						API.IMAGEURL
								+ jo.getJSONObject(i).getString("thumbfiles"),
						API.IMAGEURL
								+ jo.getJSONObject(i).getString("uploadfiles"),
						toCoverView);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	private void addViewToGrid(LinearLayout container, String url,
			String hdUrl, OnClickListener toCoverView) {
		if (TextUtils.isEmpty(url)) {
			TextView iv = new TextView(container.getContext());
			iv.setText("当前用户还没有上传图片");
			container.addView(iv);
			return;
		}
		ImageView iv = new ImageView(container.getContext());

		int width_item = container.getHeight();
		int height_item = width_item;

		iv.setOnClickListener(toCoverView);
		iv.setTag(hdUrl);
		iv.setScaleType(ScaleType.CENTER_CROP);
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				width_item - 2 * 2, height_item - 2 * 2);
		params.setMargins(2, 2, 2, 2);

		iv.setLayoutParams(params);
		container.addView(iv, params);
		App.mFBitmap.display(iv, url);

	}

	private OnClickListener toCoverView = new OnClickListener() {
		PotinToCover mPotinToCover = new PotinToCover();

		@Override
		public void onClick(View v) {

			if (v.getTag() == null || TextUtils.isEmpty(v.getTag().toString())) {
				SelectPictureActivity.pickImage(getActivity(),
						SelectPictureActivity.REQUESTCODE_TAKE_ALBUM);
			}
			else {
				ImageView cover = (ImageView) getActivity().getWindow()
						.getDecorView().findViewWithTag("COVNER");
				if (cover == null) {
					FrameLayout window = (FrameLayout) getActivity()
							.getWindow().getDecorView();
					cover = new ImageView(getActivity());
					FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
							FrameLayout.LayoutParams.MATCH_PARENT,
							FrameLayout.LayoutParams.MATCH_PARENT);
					params.gravity = Gravity.CENTER;
					cover.setLayoutParams(params);
					cover.setTag("COVNER");
					window.addView(cover);
				}
				try {
					Bitmap thumb = AlbumFragment
							.drawableToBitmap(((ImageView) v).getDrawable());
					if (thumb != null) {
						cover.setImageBitmap(thumb);
						App.mFBitmap.configLoadingImage(thumb);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				mPotinToCover.zoomImageFromThumb((ViewGroup) getActivity()
						.getWindow().getDecorView(), v, cover,
						R.drawable.image_18);
				App.mFBitmap.display(cover, v.getTag().toString());
			}

		}
	};
}
